<?php
namespace App\Services;

use App\Models\SMSVerifyData;
use Illuminate\Support\Facades\Log;

/**
 *
 * 短信发送服务层
 *
 * @author maqu
 *
 */
class SMSService extends BaseService {

    public function sendCode($phone,$extraparam){

        $time = gmtime();

        $log = SMSVerifyData::where('mobile',$phone)
            ->where('codetype',$extraparam)
            ->where('status',0)
            ->orderBy('create_time','desc')
            ->first();

        $code = '';
        if ($log) {
            if ($log->create_time + 1800 > $time) {
                $code = $log->code;
            }
        }

        if (empty($code)) {
            $code = $this->generateSMSCode(6);

            $verirydata = new SMSVerifyData();
            $verirydata->mobile =$phone;
            $verirydata->codetype =$extraparam;
            $verirydata->status =0;
            $verirydata->code =$code;
            $verirydata->create_time =$time;
            $verirydata->expire_time =$time + 1800;

            $verirydata->save();

        }

        //短信发送
        $result = $this->sendsms($phone,$code);

        unset($time,$log,$code);

        return $result;
    }

    public function checkCode($phone,$extraparam,$code){

        $time = gmtime();

        $result =[
            'result'=>false,
            'msg'=>''
        ];

        if(config('maqu.DEMO_ACCOUNT_ON')){
            if($phone=='13656816082' && $code=='123456'){
                $result['result']=true;
                return $result;
            }
        }

        $log = SMSVerifyData::where('mobile',$phone)
            ->where('codetype',$extraparam)
            ->where('status',0)
            ->orderBy('create_time','desc')
            ->first();

        if(!$log){
            $result['msg']='请先获取验证码';
        }elseif($log->code != $code){
            $result['msg']='输入的验证码不匹配';
        } elseif($log->expire_time < $time){
            $result['msg']='验证码已过期，请重新获取';
        }elseif($log->status != 0){
            $result['msg']='验证码已使用，请重新获取';
        } else{

            $log->status =1;
            $log->verify_time=$time;

            $log->save();

            $result['result']=true;
        }
        unset($time,$log);

        return $result;

    }

    public function fakeCheck($phone,$extraparam,$code){

        $time = gmtime();

        $result =[
            'result'=>false,
            'msg'=>''
        ];

        $log = SMSVerifyData::where('mobile',$phone)
            ->where('codetype',$extraparam)
            ->where('status',0)
            ->orderBy('create_time','desc')
            ->first();

        if(!$log){
            $result['msg']='请先获取验证码';
        }elseif($log->code != $code){
            $result['msg']='输入的验证码不匹配';
        } elseif($log->expire_time < $time){
            $result['msg']='验证码已过期，请重新获取';
        }elseif($log->status != 0){
            $result['msg']='验证码已使用，请重新获取';
        } else{
            $result['result']=true;
        }

        unset($time,$log);

        return $result;

    }

    //验证码
    private function generateSMSCode($len) {

        if(config('maqu.APP_DEBUG',false)){
            return '123456';
        } else {
            $code = '';
            for ($i=0; $i < $len; $i++) {
                $code = $code . rand(0, 9);
            }

            return $code;
        }

    }

    public function sendsms($phones,$code){

        $phonestr ='';
        if(is_array($phones)){
            $phonestr =implode(',',$phones);
        } else {
            $phonestr=$phones;
        }

        include base_path('vendor')."/taobao/alidayu/TopSdk.php";

        $sign_name = config('maqu.SMS_ALIDAYU_PRODUCT_NAME');

        $c = new \TopClient;
        $c->appkey = config('maqu.SMS_ALIDAYU_APPKEY');
        $c->secretKey =  config('maqu.SMS_ALIDAYU_APPSECRET');
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $c->format='json';
        $req->setSmsType("normal");
        $req->setSmsFreeSignName($sign_name);
        $req->setSmsParam("{\"code\":\"$code\",\"product\":\"$sign_name\"}");
        $req->setRecNum($phonestr);
        $req->setSmsTemplateCode(config('maqu.SMS_ALIDAYU_TEMPLATE_CODE'));

        $resp = $c->execute($req);

        if(!$resp){
            return $this->failure('短信服务器异常');
        }

        if(property_exists($resp,'code')){
//            Log::error("短信发送失败! code:$resp->code msg:$resp->msg sub_code:$resp->sub_code sub_msg:$resp->sub_msg");
            Log::error("短信发送失败! code:$resp->code msg:$resp->msg");
            return $this->failure('短信发送失败');
        } else {
            if($resp->result->success){
                return $this->success(null);
            } else {
                return $this->failure('短信发送失败');
            }
        }
    }
}